package com.jn.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CommonUtils {

	public static boolean isEmpty(Object obj) {
		if (obj == null || obj.toString().equals("")) {
			return true;
		}
		return false;
	}

	public static String convertStr(Object obj) {
		if (isEmpty(obj)) {
			return "0";
		} else {
			return String.valueOf(obj);
		}
	}

	/**
	 * @Title addQuery
	 * @Description 封装查询条件
	 * @param sb
	 * @param queryMap
	 * @param alias
	 * @return
	 * @throws
	 */
	public static StringBuffer addQuery(StringBuffer sql,
			Map<String, String> queryMap, String alias) {
		Set set = queryMap.keySet();
		Iterator it = set.iterator();
		while (it.hasNext()) {
			String key = it.next().toString();
			String value = queryMap.get(key);
			if (!isEmpty(value)) {
				if (isEmpty(alias)) {
					if (key.endsWith("date")) {
						sql.append(" and " + key + " like '"
								+ removeSpeChar(value) + "%' ");
					} else {
						sql.append(" and " + key + "='" + removeSpeChar(value)
								+ "' ");
					}
				} else {
					if (key.endsWith("date")) {
						sql.append(" and " + alias + "." + key + " like '"
								+ removeSpeChar(value) + "%' ");
					} else {
						sql.append(" and " + key + "='" + removeSpeChar(value)
								+ "' ");
					}
				}
			}
		}
		return sql;
	}

	public static String removeSpeChar(String str) {
		return str.replaceAll("-", "");
	}

	public static String count(List<String> proNums) {
		int result = 0;
		for (String num : proNums) {
			if (isNum(num)) {
				result += Integer.parseInt(num);
			}
		}
		return String.valueOf(result);
	}

	public static boolean isNum(String str) {
		if (isEmpty(str)) {
			return false;
		}
		return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
	}

	public static int getPageByCount(int totalCount) {
		int pageNum = 0;
		if (totalCount % 10 == 0) {
			pageNum = totalCount / 10;
		} else {
			pageNum = totalCount / 10 + 1;
		}
		return pageNum;
	}

	public static String pojoListToJson(List list) {
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < list.size(); i++) {
			Object pojo = list.get(i);
			sb.append(pojoToJson(pojo));
			if (i != list.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]");
		return sb.toString();
	}

	public static String pojoToJson(Object pojo) {
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		String[] fields = getFiledName(pojo);
		for (int i = 0; i < fields.length; i++) {
			String field = fields[i];
			sb.append("\"").append(field).append("\":");
			boolean flag =getFieldType(pojo, field).equals("int");
			if(!flag){
				sb.append("\"");
			}
			sb.append(getFieldValueByName(field, pojo));
			if(!flag){
				sb.append("\"");
			}
			if (i != fields.length - 1) {
				sb.append(",");
			}
		}
		sb.append("}");
		return sb.toString();
	}

	private static String getFieldType(Object o, String filedName) {
		Field[] fields = o.getClass().getDeclaredFields();
		for (Field f : fields) {
			if (f.getName().equals(filedName)) {
				return f.getType().toString();
			}
		}
		return "undefined";
	}

	/**
	 * @Title getFiledName
	 * @Description 获取属性名数组
	 * @param o
	 * @return
	 * @throws
	 */
	private static String[] getFiledName(Object o) {
		Field[] fields = o.getClass().getDeclaredFields();
		String[] fieldNames = new String[fields.length];
		for (int i = 0; i < fields.length; i++) {
			fieldNames[i] = fields[i].getName();
		}
		return fieldNames;
	}

	/**
	 * @Title getFieldValueByName
	 * @Description 根据属性名获取属性值
	 * @param fieldName
	 * @param o
	 * @return
	 * @throws
	 */
	private static Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {
			return null;
		}
	}

	public static void main(String[] args) {
		System.out.println(getDateByDay("2013-11-02").get("monthStart"));
	}

	/**
	 * @Title getDateByDay
	 * @Description 查找日期所在周、月
	 * @param applyDate
	 * @return
	 * @throws
	 */
	public static Map<String, String> getDateByDay(String applyDate) {
		Map<String, String> resultMap = new HashMap<String, String>();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date d = null;
		try {
			d = format.parse(applyDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(d);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
		resultMap.put("weekEnd", format.format(cal.getTime()));
		cal.add(Calendar.WEEK_OF_MONTH, -1);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
		resultMap.put("weekStart", format.format(cal.getTime()));

		cal.setTime(d);
		resultMap.put("monthStart",
				applyDate.substring(0, applyDate.lastIndexOf("-") + 1)
						+ addZero(cal.getActualMinimum(Calendar.DAY_OF_MONTH)));
		resultMap.put("monthEnd",
				applyDate.substring(0, applyDate.lastIndexOf("-") + 1)
						+ addZero(cal.getActualMaximum(Calendar.DAY_OF_MONTH)));
		return resultMap;
	}

	/**
	 * @Title addZero
	 * @Description 小于10的自然数补0 1-->01
	 * @param num
	 * @return
	 * @throws
	 */
	public static String addZero(int num) {
		if (num < 10) {
			return "0" + num;
		}
		return "" + num;
	}

}
